package com.tao.listener;


import com.rabbitmq.client.Channel;
import com.tao.common.utils.JsonUtil;
import com.tao.common.utils.MailUtil;
import com.tao.dataobject.EmailUserInfo;
import io.lettuce.core.dynamic.annotation.Key;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Slf4j
@Component
public class UserQueueListener {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    MailUtil mailUtil;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "userQueue", durable = "true"),
            exchange = @Exchange(value = "userExchange", type = ExchangeTypes.TOPIC),
            key = {"successful.registration"}
    ))
    public void handler(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 将Json字符串转换成对象
            String body = new String(message.getBody());
            log.info("接收到注册成功信息: {}", body);
            EmailUserInfo emailUserInfo = JsonUtil.parseObject(body, EmailUserInfo.class);
            // 发送邮件
            log.info("邮件发送成功, to: {}, name: ", emailUserInfo.getEmail(), emailUserInfo.getUserName());
            mailUtil.send(emailUserInfo.getEmail(),"感谢注册九州博客系统" , send(emailUserInfo.getUserName()));
            channel.basicAck(deliveryTag, true);
        }catch (Exception e) {
            log.info("发送邮件失败,e : {}", e);
            channel.basicNack(deliveryTag, false, true);
        }

    }

    /**
     * 根据用户名拼接注册成功文档
     */
    public String send(String userName) throws MessagingException, UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder();
        builder.append("尊敬的").append(userName).append(", 您好!").append("<br/>");
        builder.append("感谢您注册成为我们博客社区的一员! 我们很高新您加入我们的大家庭!<br/>");
        builder.append("您的注册信息如下: 用户名: ").append(userName).append("<br/>");
        builder.append("为了确保您的账⼾安全，请妥善保管您的登录信息. 如果使⽤过程中, 遇到任何问题, 欢迎联系我们的⽀持团队. 2731538103@bite.com <br/>");
        builder.append("再次感谢您的加⼊，我们期待看到您的精彩内容！<br/>")
                .append("最好的祝愿<br/>")
                .append("九州博客团队").toString();
        return builder.toString();
    }
}
